﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace Hibiku.IO
{
    public static class PropertiesReader
    {
        private static readonly Regex s_commentPattern = new Regex(@"\s*#", RegexOptions.Compiled);
        private static readonly Regex s_propertyPattern = new Regex(@"(\S+)\s*=\s*(\S+)", RegexOptions.Compiled);

        public static IDictionary<string, string> ReadPath(string path)
        {
            var properties = new Dictionary<string, string>();

            foreach (var line in File.ReadAllLines(path))
            {
                if (!s_commentPattern.IsMatch(line))
                {
                    var matches = s_propertyPattern.Match(line);

                    if (matches != null && matches.Groups.Count == 3)
                    {
                        try
                        {
                            var key = matches.Groups[1].Value;
                            var value = matches.Groups[2].Value;

                            properties.Add(key, value);
                        }
                        catch (Exception ex)
                        {
                            Trace.Write(string.Format("Failed to parse '{0}': {1}", line, ex.Message));
                        }
                    }
                }
            }

            return properties;
        }
    }
}
